package io.gitee.yanbinchen;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author: alex
 * @since : 2025-02-28 18:08
 */
public class BizUtils {

    public static final int size = 1024;

    public static byte[] zip(byte[] bytes){
        if (bytes.length>size){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try(GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
                gzip.write(bytes);
            }catch (Exception e){
                throw new SuperCacheException(-1,"Compression failed");
            }
            return bos.toByteArray();
        }
        return bytes;
    }

    public static byte[] unzip(byte[] data) {
        if (isCompressed(data)) {
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            try (GZIPInputStream gzip = new GZIPInputStream(bis);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = gzip.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                return bos.toByteArray();
            } catch (Exception e) {
                throw new SuperCacheException(-1,"Decompression failed");
            }
        }
        return data;
    }

    private static boolean isCompressed(byte[] data) {
        return data.length > 2 && (data[0] == (byte) 0x1F && data[1] == (byte) 0x8B);
    }
}
